package com.mifengs.mall.util;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import com.mifengs.commonbase.util.PreferenceUtils;
import com.mifengs.mall.entity.ImageUpload;
import com.mifengs.mall.netWork.NetWork;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import rx.Observable;
import rx.Observer;
import rx.Scheduler;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by lihaoqi on 2018/3/23.
 */

public class UploadImgUtil {

    public static final long maxUploadLength = 5*1024*1024;

    private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");

    public static Subscription upLoadImg(String imgUrls,Observer<ImageUpload> callBack) {
        // mImgUrls为存放图片的url集合
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        File f=new File(imgUrls);
        if (f!=null) {
            builder.addFormDataPart("fileList", f.getName(), RequestBody.create(MEDIA_TYPE_PNG, f));
        }
        builder.addFormDataPart("app_token", PreferenceUtils.getToken());
        builder.addFormDataPart("attachmentType","SIGNATURE");
        List<MultipartBody.Part> parts = builder.build().parts();
        Subscription subscription = NetWork.getImageUploadApi().uploadFiles(parts)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(callBack);
//                .subscribe(new Observer<ImageUpload>() {
//                    @Override
//                    public void onCompleted() {
//
//                    }
//
//                    @Override
//                    public void onError(Throwable e) {
//                        System.out.println("上传失败:e.getLocalizedMessage() = " + e.getLocalizedMessage());
//                    }
//
//                    @Override
//                    public void onNext(ImageUpload imageUpload) {
//                        if(imageUpload.getMsg().equals("OK") && imageUpload.getStatus().equals("1")){
//                            System.out.println("上传照片成功：url = " + imageUpload.getResult().getPic());
//                        }
//                    }
//                });
        return subscription;
    }

    public static Observable upLoadImg(String imgUrls){
        // mImgUrls为存放图片的url集合
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        File f=new File(imgUrls);
        if (f!=null) {
            builder.addFormDataPart("fileList", f.getName(), RequestBody.create(MEDIA_TYPE_PNG, f));
        }
        builder.addFormDataPart("app_token", PreferenceUtils.getToken());
        builder.addFormDataPart("attachmentType","SIGNATURE");
        List<MultipartBody.Part> parts = builder.build().parts();
        return NetWork.getImageUploadApi().uploadFiles(parts)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    };

    public static Observable upLoadCompressImg(String imgUrls){
        // mImgUrls为存放图片的url集合
//        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
//        File f=new File(imgUrls);
//        if (f!=null) {
//            builder.addFormDataPart("fileList", f.getName(), RequestBody.create(MEDIA_TYPE_PNG, f));
//        }
//        builder.addFormDataPart("app_token", PreferenceUtils.getToken());
//        builder.addFormDataPart("attachmentType","SIGNATURE");
//        List<MultipartBody.Part> parts = builder.build().parts();
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        byte[] imgBytes;
        File f=new File(imgUrls);
        if(f.length()>maxUploadLength){
            imgBytes = qualityCompress(imgUrls);
            builder.addFormDataPart("fileList", f.getName(), RequestBody.create(MEDIA_TYPE_PNG,imgBytes));
        }else{
            builder.addFormDataPart("fileList", f.getName(), RequestBody.create(MEDIA_TYPE_PNG,f));
        }
        builder.addFormDataPart("app_token", PreferenceUtils.getToken());
        builder.addFormDataPart("attachmentType","SIGNATURE");
        List<MultipartBody.Part> parts = builder.build().parts();
        return NetWork.getImageUploadApi().uploadFiles(parts);
    };


//    public static Observable<String> creatCompressImgObservable(final String imgFilePath, final Observer<ImageUpload> callBack){
//
//        return  Observable.create(new Observable.OnSubscribe<String>() {
//
//            @Override
//            public void call(Subscriber<? super String> subscriber) {
//                try {
//                    MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
//                    byte[] imgBytes;
//                    File f=new File(imgFilePath);
//                    if(f.length()>maxUploadLength){
//                        imgBytes = qualityCompress(imgFilePath);
//                        builder.addFormDataPart("fileList", f.getName(), RequestBody.create(MEDIA_TYPE_PNG,imgBytes));
//                    }else{
//                        builder.addFormDataPart("fileList", f.getName(), RequestBody.create(MEDIA_TYPE_PNG,f));
//                    }
//                    builder.addFormDataPart("app_token", PreferenceUtils.getToken());
//                    builder.addFormDataPart("attachmentType","SIGNATURE");
//                    List<MultipartBody.Part> parts = builder.build().parts();
//                    NetWork.getImageUploadApi().uploadFiles(parts)
//                            .subscribeOn(Schedulers.io())
//                            .observeOn(AndroidSchedulers.mainThread())
//                            .subscribe(callBack);
//                    subscriber.onNext("success");
//                    subscriber.onCompleted();
//                } catch (Exception e) {
//                    subscriber.onError(e);
//                }
//            }
//        });
//    }


    public static Observable upCompressImg(String imageurl){
       return Observable.just(imageurl)
               .concatMap(new Func1<String,Observable<ImageUpload>>() {
                   @Override
                   public Observable<ImageUpload> call(String imgUrls) {
                       MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
                       byte[] imgBytes;
                       File f=new File(imgUrls);
                       if(f.length()>maxUploadLength){
                           imgBytes = qualityCompress(imgUrls);
                           builder.addFormDataPart("fileList", f.getName(), RequestBody.create(MEDIA_TYPE_PNG,imgBytes));
                       }else{
                           builder.addFormDataPart("fileList", f.getName(), RequestBody.create(MEDIA_TYPE_PNG,f));
                       }
                       builder.addFormDataPart("app_token", PreferenceUtils.getToken());
                       builder.addFormDataPart("attachmentType","SIGNATURE");
                       List<MultipartBody.Part> parts = builder.build().parts();
                       return NetWork.getImageUploadApi().uploadFiles(parts);
                   }
               }).subscribeOn(Schedulers.io())
               .observeOn(AndroidSchedulers.mainThread());
    }







    public static byte[] qualityCompress(String filePath) {
        // 0-100 100为不压缩
        int quality = 100;
        File f=new File(filePath);
        if(f.length()> maxUploadLength){
           // quality = (int)(f.length()/maxUploadLength)*100;
            long fileLength = f.length();

            double q = Math.pow((double) maxUploadLength/fileLength,1.0/3.0);

            quality = (int)(q*100);

            if(quality>100) quality=100;

          //  quality = (maxUploadLength/fileLength)*100;
        }
        f.length();
        byte[] imgBytes;
        Bitmap bmp = BitmapFactory.decodeFile(filePath);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // 把压缩后的数据存放到baos中
        bmp.compress(Bitmap.CompressFormat.JPEG, quality, baos);
        imgBytes = baos.toByteArray();
        return imgBytes;
    }



}
